package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends BaseServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
        @Autowired
        private FastDFSClient client;

        @Value("${fdfs.url}")
        private String baseUrl;

        @Autowired
        private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile==null) return paramError;
        try {
            String s = client.uploadFile(multipartFile);
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(s);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            //通过线程副本获取uid
            wmMaterial.setUserId(WmThreadLocalUtils.getUserId());
            save(wmMaterial);
            wmMaterial.setUrl(baseUrl+s);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult("上传成功");
    }

    @Override
    public ResponseResult downloadPicture(String groupName, String path) {
//        path=baseUrl+path;
        try {
            client.download(groupName,path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult("下载成功");
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        if (id==null) return paramError;
        WmMaterial material = getById(id);
        if (material==null) return notExits;
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        //判断是否有关联，新闻与图片是否关联
        if (count>0){
            return ResponseResult.okResult(0,"该资源与其他资源有关联，不让删");
        }
        //删文件,以防万一，去掉前缀(有则删，没有也不执行)
        String realFile = material.getUrl().replace(baseUrl, "");
        try {
            client.delFile(realFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //删数据
        removeById(id);
        return paramSuccess;
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto==null) return paramError;
        Integer userId = WmThreadLocalUtils.getUserId();
        if (userId==null) return needLogin;
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId,userId);
        if (dto.getIsCollection()!=null) wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        ResponseResult pageResult = getPageResult(dto, wrapper);
        List<WmMaterial> data= (List<WmMaterial>) pageResult.getData();
        for (WmMaterial material : data) {
            material.setUrl(baseUrl+material.getUrl());
        }
        pageResult.setData(data);
        return pageResult;
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id==null) return paramError;
        //获取ap_userId
        Integer userId = WmThreadLocalUtils.getUserId();
        //更改用户状态
        WmMaterial material = new WmMaterial();
        material.setId(id);
        material.setType(type);
        updateById(material);
        return paramSuccess;
    }
}
